﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;

namespace Eggplant.Web.Rest
{
	public class RestHttpApplication : System.Web.HttpApplication
	{
		public RestHttpApplication()
		{
			this.Error += new EventHandler(OnError);
		}

		public virtual bool AllowDefaultErrors
		{
			get { return false; }
		}

		void OnError(object sender, EventArgs e)
		{
			if (AllowDefaultErrors)
				return;

		    Exception ex = this.Server.GetLastError();
		    if (ex is TargetInvocationException)
		    {
		        ex = ex.InnerException;
		    }
			this.Server.ClearError();
            
		    if (ex is HttpException)
		    {
                HttpManager.SetResponse(this.Context, (System.Net.HttpStatusCode) ((HttpException)ex).GetHttpCode(), GetErrorObject(ex));
		    }
            else
			    HttpManager.SetResponse(this.Context, System.Net.HttpStatusCode.InternalServerError, GetErrorObject(ex));
		}

		protected virtual object GetErrorObject(Exception ex)
		{
			return ex;
		}
	}
}
